package org.jeecg.modules.bobo.wechat.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.result.WxPayBillInfo;
import com.github.binarywang.wxpay.bean.result.WxPayBillResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.jeecg.modules.bobo.common.util.BeanUtils;
import org.jeecg.modules.bobo.wechat.common.entity.WechatDownloadbill;
import org.jeecg.modules.bobo.wechat.common.mapper.WechatDownloadbillMapper;
import org.jeecg.modules.bobo.wechat.common.service.IWechatDownloadbillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 微信对账单
 * @Author: jeecg-boot
 * @Date:   2020-11-23
 * @Version: V1.0
 */
@Service
public class WechatDownloadbillServiceImpl extends ServiceImpl<WechatDownloadbillMapper, WechatDownloadbill> implements IWechatDownloadbillService {
    @Autowired
    private WxPayService wxPayService;
    @Override
    public boolean getDownloadbill(String date) throws Exception {
        WxPayBillResult wxPayBillResult;
        try {
            wxPayBillResult = wxPayService.downloadBill(date,"ALL","" ,"");
        }catch (WxPayException wxPayException){
            return false;
        }
        //插入数据库
        List<WechatDownloadbill> weixinDownloadbills=new ArrayList<>();
        WechatDownloadbill weixinDownloadbill=null;
        //删除date当天交易记录
        if (wxPayBillResult.getBillInfoList().size() > 0) {
            List<String> tradeTimes = wxPayBillResult.getBillInfoList().stream().map(WxPayBillInfo::getTradeTime).collect(Collectors.toList());
            remove(new QueryWrapper<WechatDownloadbill>().lambda().in(WechatDownloadbill::getTradeTime,tradeTimes));
        }


        for (WxPayBillInfo item:
                wxPayBillResult.getBillInfoList()) {
            weixinDownloadbill=new WechatDownloadbill();
            BeanUtils.copyProperties(item, weixinDownloadbill);
            weixinDownloadbills.add(weixinDownloadbill);
        }
        saveBatch(weixinDownloadbills);
        return true;
    }
}
